from fastapi import FastAPI
from fastapi import Request
from fastapi.exceptions import HTTPException, RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from starlette.exceptions import HTTPException as StarletteHTTPException

from common.response import BadRequestResponse, ServerErrorResponse
from component.ConfigManager import config_manager
from component.LogManager import log_manager

logger = log_manager.get_logger("app")

# 启动 FastAPI http 服务器
app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)

logger.info(f"服务已启动：version: {config_manager.get_value('version')}")

# 引入路由
from route.organization import router as organization_router
app.include_router(organization_router, prefix="/api/v1/organization", tags=["organization"])

from route.node import router as node_router
app.include_router(node_router, prefix="/api/v1/node", tags=["node"])

from route.data import router as data_router
app.include_router(data_router, prefix="/api/v1/data", tags=["data"])

from route.analysis import router as analysis_router
app.include_router(analysis_router, prefix="/api/v1/analysis", tags=["analysis"])

from route.train_task import router as task_router
app.include_router(task_router, prefix="/api/v1/task", tags=["task"])

from route.model import router as model_router
app.include_router(model_router, prefix="/api/v1/model", tags=["model"])

from route.base import router as base_router
app.include_router(base_router, prefix="/api/v1", tags=["base"])


@app.on_event("startup")
async def startup_event():
    logger.info("服务启动")


@app.get("/")
async def root():
    return f"服务已部署，version：{config_manager.get_value('version')}"

# 错误处理部分代码


@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
    """
    错误处理 HTTP 错误，返回 http 400
    :param request:
    :param exc:
    :return:
    """
    logger.error(f"HTTP 错误: {exc}")
    return ServerErrorResponse(code=exc.status_code, msg="发生 http 错误" + str(exc.detail))


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc):
    """
    错误处理，请求无效错误，返回 http 500
    :param request:
    :param exc:
    :return:
    """
    logger.warning(f"收到无效 body：{exc}")
    return BadRequestResponse(msg="无效 body")
